
package com.outsourcing.bottle.ui;

import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.domain.MessageEntry;
import com.outsourcing.bottle.domain.MyMessageInfo;
import com.outsourcing.bottle.domain.OUserInfoEntry;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.widget.CustomListView;
/**
 * 
 * @author 06peng
 *
 */
public class ConversationListActivity extends BasicActivity implements Callback, OnClickListener {

	private static final int EXEU_DELETE_LOCATION_SUCCESS = 101;
	private static final int EXEU_DELETE_LOCATION_FAILED = 102;
	private static final int EXEU_DELETE_LOCATION = 103;
	private ImageView backView;
	private ImageView moreView;
//	private ImageView noticeView;
//	private LinearLayout messageCountLayout;
//	private TextView countView;
	private CustomListView listView;
	private int visibleLastIndex = 0; // 最后的可视项索引
	public int visibleItemCount; // 当前窗口可见项总数
	private View loadMoreView;
	private ImageView commentView;
	
	
	private final int init_conversation_info = 1;
	private final int error = 2;
	private final int user_baseinfo_notfull = 3;
	private final int complete_info = 4;
	private final int more = 7;
	private int page = 1;
//	private int newNoticeCount;
	
	
	private Handler handler;
	private int ouid;
	private List<MessageEntry> messageList;
	private ConversationAdapter adapter;
	private OUserInfoEntry entry;
	private Bitmap bitmap; //用户头像
//	private PushNoticeInfo pushInfo;
	
	/******* 用户资料 *********/
	private RemoteImageView avatarView;
	private TextView nicknameView;
	private TextView memoView;
	private ImageView sexView;
	private TextView doingView;
	private TextView addressView;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.conversation_list);
		handler = new Handler(this);
		ouid = getIntent().getIntExtra("ouid", 0);
		initWidget();
		UICore.eventTask(this, this, init_conversation_info, "init_conversation_info", null);
	}
	
	private void initWidget() {
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		moreView = (ImageView) findViewById(R.id.topbar_menu);
		moreView.setOnClickListener(this);
//		noticeView = (ImageView) findViewById(R.id.topbar_notice);
//		noticeView.setOnClickListener(this);
		commentView = (ImageView) findViewById(R.id.comment);
		commentView.setOnClickListener(this);
//		messageCountLayout = (LinearLayout) findViewById(R.id.notice_layout);
//		messageCountLayout.setVisibility(View.GONE);
//		countView = (TextView) findViewById(R.id.notice_count);
		listView = (CustomListView) findViewById(R.id.notice_list);
		loadMoreView = LayoutInflater.from(this).inflate(R.layout.refreshable_list_footer, null);
		loadMoreView.setVisibility(View.GONE);
		listView.addFooterView(loadMoreView);
		listView.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				page = 1;
				new Thread() {
					public void run() {
						initConversationInfo();
					};
				}.start();
			}
		});
		listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				int itemsLastIndex = adapter.getCount() + 1; // 数据集最后一项的索引
				int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {
					// 如果是自动加载,可以在这里放置异步加载数据的代码
					loadMoreView.setVisibility(View.VISIBLE);
					page++;
					new Thread() {
						@Override
						public void run() {
							loadMoreConversationInfo();
						}
					}.start();
				}	
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				listView.setFirstVisiableItem(firstVisibleItem);
				ConversationListActivity.this.visibleItemCount = visibleItemCount;
				visibleLastIndex = firstVisibleItem + visibleItemCount;
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (arg2 == adapter.getCount() + 1) {
					return;
				}
				MessageEntry entry = messageList.get(arg2 - 1);
				if (entry.getMessage_location() != null
						&& entry.getMessage_lat() != 0
						&& entry.getMessage_lng() != 0) {
					Intent intent = new Intent(ConversationListActivity.this, MapViewActivity.class);
					intent.putExtra("longitude", entry.getMessage_lng());
					intent.putExtra("latidute", entry.getMessage_lat());
					intent.putExtra("location", entry.getMessage_location());
					startActivity(intent);
				}
			}
		});
		
		avatarView = (RemoteImageView) findViewById(R.id.user_space_avatar);
		avatarView.setOnClickListener(this);
		nicknameView = (TextView) findViewById(R.id.user_space_nickname);
		memoView = (TextView) findViewById(R.id.user_space_memo);
		sexView = (ImageView) findViewById(R.id.user_space_sex);
		doingView = (TextView) findViewById(R.id.user_space_doing);
		addressView = (TextView) findViewById(R.id.user_space_address);
	}
	
	private void updateUI() {
		findViewById(R.id.conversation_layout).setVisibility(View.VISIBLE);
		commentView.setVisibility(View.VISIBLE);
		if (entry != null) {
			nicknameView.setText(entry.getOnickname());
			if (entry.getOsex() == 1) {
				sexView.setBackgroundResource(R.drawable.male);
			} else if (entry.getOsex() == 2) {
				sexView.setBackgroundResource(R.drawable.female);
			}
			if (TextUtil.notEmpty(entry.getOmemo())) {
				((TextView) findViewById(R.id.user_space_memo)).setVisibility(View.VISIBLE);
				memoView.setText("-" + entry.getOmemo());
			} else {
				((TextView) findViewById(R.id.user_space_memo)).setVisibility(View.GONE);
				memoView.setVisibility(View.GONE);
			}
			if (TextUtil.notEmpty(entry.getOcity()) &&  TextUtil.notEmpty(entry.getOcountry())) {
				addressView.setVisibility(View.VISIBLE);
				if (AppContext.language == 1) {
					addressView.setText(getString(R.string.user_from) + entry.getOcountry() + " " + entry.getOcity());
				} else {
					addressView.setText(getString(R.string.user_from) + entry.getOcity() + " " + entry.getOcountry());
				}
			} else {
				addressView.setVisibility(View.GONE);
			}
			String html = "<font color=black>"+getString(R.string.user_info_doing)+"</font>";
			doingView.setText(Html.fromHtml(html + entry.getOdoing()));
			if (bitmap != null) {
				avatarView.setImageBitmap(bitmap);
			}
		}
		if (messageList != null && !messageList.isEmpty()) {
			adapter = new ConversationAdapter();
			listView.setAdapter(adapter);
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v == backView) {
			finish();
		} else if (v == moreView) {
//			Intent intent = new Intent(this, MoreActivity.class);
//			startActivity(intent);
			Intent intent = new Intent(ConversationListActivity.this, HomeActivity.class);
			intent.putExtra("currentItem", 1);
			startActivity(intent);
			finish();
		} 
//		else if (v == noticeView) {
//			Intent intent = new Intent(this, NoticeListActivity.class);
//			startActivity(intent);
//		} 
		else if (v == commentView) {
			Intent intent = new Intent(this, ExpandEditActivity.class);
			Bundle extras = new Bundle();
			extras.putString("from_type", AppContext.SEND_MESSAGE);
			extras.putInt("ouid", ouid);
			intent.putExtras(extras);
			startActivity(intent);
		} else if (v == avatarView) {
			byte[] tempBytes = null;
			try {
				tempBytes = ServiceUtils.BitmapTobytes(bitmap);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Intent bigPicIntent = new Intent(ConversationListActivity.this, PhotoDetailActivity.class);
			bigPicIntent.putExtra("pic_big", entry.getOavatar());
			bigPicIntent.putExtra("thumbnail", tempBytes);
			startActivity(bigPicIntent);
		}
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case init_conversation_info:
			initConversationInfo();
			break;
		case EXEU_DELETE_LOCATION:
			MessageEntry messageEntry = (MessageEntry)obj;
			deleteLocation(String.valueOf(messageEntry.getLocation_objtype()),String.valueOf(messageEntry.getLocation_objid()));
			break;
		default:
			break;
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_conversation_info:
			updateUI();
			listView.onRefreshComplete();
			break;
		case user_baseinfo_notfull:
			showChoseMes(getString(R.string.exchange_complete_profile_tips), complete_info);
			break;
		case error:
			onToast((String) msg.obj);
			break;
		case more:
			adapter.notifyDataSetChanged();
			loadMoreView.setVisibility(View.GONE);
		case EXEU_DELETE_LOCATION_SUCCESS:
			 onToast((String) msg.obj);
			 
			UICore.eventTask(ConversationListActivity.this, ConversationListActivity.this, init_conversation_info, "init_conversation_info", null);
			break;
		case EXEU_DELETE_LOCATION_FAILED:
		    onToast((String) msg.obj);
			break;
		default:
			break;
		}
		return false;
	}

	/**
	 * 
	 * @param objtype 要清除的位置的类型：选择项：（1）瓶子动态的位置信息、（2）交换动态留言的位置信息、（3）照片评论的位置信息、（4）私信的位置信息、（5）照片的位置信息
	 * @param objid objid
	 */
	private void deleteLocation(String objtype,String objid) {
		StringBuffer url = new StringBuffer(UrlConfig.delete_location);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&objtype=" + objtype);
		url.append("&objid=" + objid);
		ServiceUtils.dout("deleteLocation url:" + url.toString());
		try {
			String result = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("deleteLocation result:" + result);
			JSONObject obj = new JSONObject(result);
			JSONObject resultObj = obj.getJSONObject("results");
			int success = resultObj.getInt("success");
			String errmsg = resultObj.getString("errmsg");
			String successmsg = resultObj.getString("successmsg");
			if (success == 1) {
				Message message = handler.obtainMessage(
						EXEU_DELETE_LOCATION_SUCCESS, successmsg);
				handler.sendMessage(message);
			} else {
				Message message = handler.obtainMessage(
						EXEU_DELETE_LOCATION_FAILED, errmsg);
				handler.sendMessage(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initConversationInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_mymessageslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		url.append("&count=" + 20);
		url.append("&page=" + page);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			MyMessageInfo info = gson.fromJson(result, MyMessageInfo.class);
			if (info.getResults().getAuthok() == 0) {
				Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
				handler.sendMessage(msg);
			} else {
//				PushNoticeInfoTable table = new PushNoticeInfoTable();
//				pushInfo = table.getPushNoticeInfo(AppContext.getInstance().getLogin_uid());
//				if (null!= pushInfo) {
//					newNoticeCount = pushInfo.getNew_notice_count();
//				}
				entry = info.getOuser_info();
				if (entry != null) {
					bitmap = HttpUtils.getBitmapFromUrl(ConversationListActivity.this, entry.getOavatar());
				}
				messageList = info.getMessages_list();
				handler.sendEmptyMessage(init_conversation_info);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void loadMoreConversationInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_mymessageslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		url.append("&count=" + 20);
		url.append("&page=" + page);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			MyMessageInfo info = gson.fromJson(result, MyMessageInfo.class);
			if (info.getResults().getAuthok() == 0) {
				Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
				handler.sendMessage(msg);
			} else {
				List<MessageEntry> moreList = info.getMessages_list();
				messageList.addAll(moreList);
				handler.sendEmptyMessage(more);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class ConversationAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return messageList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return messageList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			ViewHolder holder;
			if (arg1 != null && arg1.getId() == R.id.conversation_list_item_layout) {
				holder = (ViewHolder) arg1.getTag();
			} else {
				arg1 = LayoutInflater.from(getApplicationContext()).inflate(R.layout.conversation_list_item, null);
				holder = new ViewHolder();
				holder.avatarView = (RemoteImageView) arg1.findViewById(R.id.notice_item_avatar);
				holder.nameView = (TextView) arg1.findViewById(R.id.notice_item_nameandcontent);
				holder.timeView = (TextView) arg1.findViewById(R.id.notice_item_timeandlocation);
				holder.contentLayout = (LinearLayout) arg1.findViewById(R.id.notice_item_content_layout);
				arg1.setTag(holder);
			}
			final MessageEntry entry = messageList.get(arg0);
			if (entry != null) {
				holder.avatarView.setDefaultImage(R.drawable.avatar_default_big);
				holder.avatarView.setImageUrl(entry.getAvatar(), arg0, listView);
				String name = null;
				if (entry.getUid() == AppContext.getInstance().getLogin_uid()) {
					name = "<font color=#419AD9>" + entry.getNickname() + "</font>";
					holder.contentLayout.setBackgroundResource(R.drawable.frame_yellow);
				} else {
					name = "<font color=red>" + entry.getNickname() + "</font>";
					holder.contentLayout.setBackgroundResource(R.drawable.frame_gray);
				}
				holder.nameView.setText(Html.fromHtml(name + "&nbsp;" + TextUtil.htmlEncode(entry.getContent())));
				String time = (!TextUtils.isEmpty(entry.getMessage_time()))?"#"+entry.getMessage_time():"";
				String location = (!TextUtils.isEmpty( entry.getMessage_location()))?"@"+ entry.getMessage_location():"";
				holder.timeView.setText(Html.fromHtml(time + " " +location));
				if (!TextUtils.isEmpty(location)) {
					holder.timeView.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {

								if(entry.getLocation_delete_enable() == 1){
									final Context dialogContext = new ContextThemeWrapper(
											ConversationListActivity.this,
											android.R.style.Theme_Light);
									String[] choices = new String[2];
									choices[0] = getString(R.string.bottle_txt_check_location);
									choices[1] = getString(R.string.bottle_txt_clean_location);

									final ListAdapter adapter = new ArrayAdapter<String>(
											dialogContext,
											android.R.layout.simple_list_item_1,
											choices);

									final AlertDialog.Builder builder = new AlertDialog.Builder(
											dialogContext);
									builder.setTitle(R.string.system_info);
									builder.setSingleChoiceItems(
											adapter,
											-1,
											new DialogInterface.OnClickListener() {

												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
													if (which == 0) {
														dialog.dismiss();
														Intent intent = new Intent(
																ConversationListActivity.this,
																MapViewActivity.class);
														intent.putExtra("longitude",entry.getMessage_lng());
														intent.putExtra("latidute",entry.getMessage_lat());
														intent.putExtra("location",entry.getMessage_location());
														startActivity(intent);
													} else {
														UICore.eventTask(ConversationListActivity.this, ConversationListActivity.this, EXEU_DELETE_LOCATION, "", entry);
													}

												}
											});
									builder.create().show();
							} else {
								final Context dialogContext = new ContextThemeWrapper(
										ConversationListActivity.this,
										android.R.style.Theme_Light);
								String[] choices = new String[1];
								choices[0] = getString(R.string.bottle_txt_check_location);

								final ListAdapter adapter = new ArrayAdapter<String>(
										dialogContext,
										android.R.layout.simple_list_item_1,
										choices);

								final AlertDialog.Builder builder = new AlertDialog.Builder(
										dialogContext);
								builder.setTitle(R.string.system_info);
								builder.setSingleChoiceItems(adapter, -1,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
												Intent intent = new Intent(
														ConversationListActivity.this,
														MapViewActivity.class);
												intent.putExtra("longitude",entry.getMessage_lng());
												intent.putExtra("latidute",entry.getMessage_lat());
												intent.putExtra("location",entry.getMessage_location());
												startActivity(intent);
											}
										});
								builder.create().show();
								}
							
						}
					});		
				}
			}
			return arg1;
		}
		
	}
	
	public static class ViewHolder {
		RemoteImageView avatarView;
		TextView nameView;
		TextView timeView;
		LinearLayout contentLayout;
	}
	
	@Override
	public void sysMesPositiveButtonEvent(int what) {
		if (what == complete_info) {
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);
		} 
	}
}
